﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace NoticeHelper.Dingtalk.DingtalkCustomRobotSdk
{
    public class DingtalkOptions
    {
        public string UrlBase { get; set; }
        public string Secret { get; set; }
        public string RequestUrl => Secret == default ? UrlBase : GetUrl(UrlBase, Secret);

        private static string GetUrl(string url, string secret)
        {
            var timeStamp = (DateTimeOffset.Now.UtcTicks - 621355968000000000) / 10000;
            var stringToSign = $"{timeStamp}\n{secret}";
            var b64 = GetHmac(stringToSign, secret);
            var b64Str = Convert.ToBase64String(b64);
            var sign = HttpUtility.UrlEncode(b64Str, Encoding.UTF8);
            var newUrl = $"{url}&timestamp={timeStamp}&sign={sign}";
            return newUrl;
        }

        private static byte[] GetHmac(string message, string secret)
        {
            byte[] keyByte = Encoding.UTF8.GetBytes(secret);
            byte[] messageBytes = Encoding.UTF8.GetBytes(message);
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                return hashmessage;
            }
        }
    }
}
